<?php
/**
 * Vip用户相关
 *
 * @author  
 * @time 2024-01-23 14:06:36
 */

namespace App\Repositories;

use App\Constant\UserLevel;
use App\Exceptions\AuthorizationRepoException;
use App\Exceptions\RepoException;
use App\Models\AiLawUsers;
use App\Models\AiLawVipUsers;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class VipUserRepo
{
    public function consumeUserQuestionTimes()
    {
        $user = AiLawVipUsers::query()->where('user_id', Auth::id())->first();
        if (empty($user->id)) {
            throw new RepoException("您还不是会员，请充值会员获取更多次数。");
        }
        if ($user->user_level == UserLevel::NORMAL_USER) {
            if ($user->robot_question_times == 0) {
                throw new RepoException("您的体验次数已用完，请充值会员获取更多次数。");
            }
            $row = AiLawVipUsers::query()
                ->where('user_id', Auth::id())
                ->whereRaw("robot_question_times > 0 ")
                ->update(['robot_question_times' => DB::raw("robot_question_times-1")]);
            if ($row == 0) {
                throw new RepoException("您的体验次数已不足，请充值会员获取更多次数。");
            }
        }

    }

    /**
     * 校验会员情况
     *
     * @return true
     * @throws RepoException
     * @author  
     * @time 2024-01-29 11:56:11
     */
    public function validateUserPermissionForUseAiRobot()
    {
        $user = AiLawVipUsers::query()->where('user_id', Auth::id())->first();
        if (empty($user->id)) {
            throw new AuthorizationRepoException("您还不是会员，请先充值。");
        }

        if (!empty($user->vip_expire_at)) {
            $isExpired = Carbon::parse($user->vip_expire_at)->isBefore(Carbon::now());
            if ($isExpired) {
                throw new AuthorizationRepoException("您的会员已过期，请您续费会员。");
            }
        }

        if (empty($user->robot_question_times)) {
            throw new AuthorizationRepoException("您的体验次数已用完，请先充值会员。");
        }

        return true;
    }

    /**
     * 获取用户中台token
     *
     * @return array
     * @throws RepoException
     * @author  
     * @time 2024-01-30 11:37:38
     */
    public function getUserAIToken()
    {
        $this->validateUserPermissionForUseAiRobot();

        $user = AiLawUsers::query()->where('id', Auth::id())->first();
        return ['token' => $user->ai_token];
    }


}